import sys, os.path
sys.path.append('../..')
import HiroSQL
sys.path.append(HiroSQL.__name__+'/external')
sys.path.append(HiroSQL.__name__)
import  traceback, time
#from config import Config

try:
    True
except NameError:
    True = (1==1)
    False = (1==0)
    
__version__ = HiroSQL.__version__


class ServiceWrapper:
    def __init__(self, database, driver, create=False, catchErrors=True, header="HiroSQL Console", locals=None):
        print 'database:',database,'driver:',driver
        #code.InteractiveConsole.__init__(self, locals, header)
        self.database = database
        self.driver = driver
        self.create = create        
        self.catchErrors = catchErrors		

        self.datadir = Config.defaultServerSetting['datadir']
		
		
    def execute(self, sql):

        connection = HiroSQL.connect(self.database, self.datadir, driver=self.driver, autoCreate=self.create)
        cursor = connection.cursor()
        start = time.time()
        cursor.execute(sql)
        results = cursor.info['results']
        end = time.time()

        t = end - start
		
        result = []
		
        status = 1
        header = cursor.info['columns']
        if not cursor.info['results']:
			content = []
        else:
			content = cursor.info['results']
        affectedRows = cursor.info['affectedRows']
        usedTime = t
        info = None
		
        result.append(status)
        result.append(header)
        result.append(content)
        result.append(affectedRows)
        result.append(usedTime)
        result.append(info)
		

        connection.commit()
        connection.close()
        return result
		
if __name__ == '__main__':
	from config import Config
	setattr(__builtins__, 'Config', Config)
	a=Config()
	a.loadServer()
	c = ServiceWrapper('test1', 'dbm')
	#c.execute('CREATE TABLE Person (LastName String REQUIRED, FirstName String)')
	result = c.execute('INSERT INTO Person(LastName,FirstName) VALUES(\'zhu\',\'ze\')')
	print 'insert',result	
	result = c.execute('select * from Person')
	print 'select',result
